#pragma once
#include <signal.h>
#include <iostream>
#include <functional>
#include "log.hpp"
#include "Socket.hpp"
using func_t = std::function<std::string(std::string &package)>;
class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : port_(port), callback_(callback)
    {
    }
    ~TcpServer()
    {
    }

public:
    bool InitServer()
    {
        listensockfd_.Socket();
        listensockfd_.Bind(port_);
        listensockfd_.Listen();
        log(Info, "Init server...normal");
        return true;
    }
    void Start()
    {
        while (true)
        {
            signal(SIGCHLD, SIG_IGN);
            signal(SIGPIPE, SIG_IGN);
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensockfd_.Accept(&clientip, &clientport);
            if (sockfd == -1)
                continue;
            log(Info, "Accept a new link,sockfd:%d,clientip:%s,clientport:%d", sockfd, clientip.c_str(), clientport);
            // 子进程提供服务
            if (fork() == 0)
            {
                listensockfd_.Close();
                std::string inbuffer_stream;
                // 计算
                while (true)
                {
                    char buffer[128];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        log(Debug, "Debug:%s", inbuffer_stream.c_str());
                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);
                            if (info.empty())
                                break;
                            log(Debug, "debug, response:\n%s", info.c_str());
                            log(Debug, "debug:\n%s", inbuffer_stream.c_str());
                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n == 0)
                        break;
                    else
                        break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    uint16_t port_;
    MySocket listensockfd_;
    func_t callback_;
};